package com.spirng.leetcode.day06;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class Test116 {
    public static void main(String[] args) {

    }
    public static Node2 connect(Node2 root) {
        Queue<Node2> queue=new LinkedList<>();
        if(root==null)
        {
            return root;
        }
        queue.offer(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Node2 node2 = queue.remove();
                if(i==size-1){
                    node2.next=null;
                }
                node2.next=queue.peek();
                if(node2.left!=null) queue.add(node2.left);
                if(node2.right!=null) queue.add(node2.right);
            }
        }
        return root;
    }
}

// Definition for a Node.
class Node2 {
    public int val;
    public Node2 left;
    public Node2 right;
    public Node2 next;

    public Node2() {}

    public Node2(int _val) {
        val = _val;
    }

    public Node2(int _val, Node2 _left, Node2 _right, Node2 _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
